import React from 'react'
import PropTypes from 'prop-types'
import {Modal, Form, Input, Select, Col, message} from 'antd';
import axios from "axios";
import api from "../../../../api/api";

const FormItem = Form.Item;

const {Option} = Select;

@Form.create()
class Model extends React.Component {
    //继承父页面，取数据
    constructor(props) {
        super(props)
        this.state = {
            param: {
                gid: "",
                code: "",
                fullName: "",
                name: "",
                thirdDepartmentId: "",
                thirdFactoryId: "",
                pcode: "",
                orgCode: localStorage.getItem("orgCode"),
                createTime: "",
                guiKouFlag: ""
            },
        };
    }

    //初始化页面数据
    componentDidMount() {
        this.clearData()
        this.props.onRef(this)
        this.companyChange();
    }

    //form表单提交数据
    handleOk = () => {
        this.props.form.validateFields((error, values) => {
            if (error != null) {
                return;
            }
            let {param} = this.state
            param.code = values.code
            param.fullName = values.fullName
            param.name = values.name
            param.thirdFactoryId = values.thirdFactoryId;
            param.gid = values.gid;
            this.setState({param}, () => {
                this.departMentData()
            })
        })
    }
    setBaseInfo = () => {
        let data = this.props.data.gridList
        const {form} = this.props;
        Object.keys(form.getFieldsValue()).forEach(key => {
            const obj = {};
            if (data[key]) {
                obj[key] = data[key] || null;
            }
            form.setFieldsValue(obj);
        });
    };

    //清空form表单数据
    clearData() {
        this.props.form.resetFields();
    }

    //初始化编辑数据
    initEditData = () => {
        this.setBaseInfo()
    }

    departMentData() {
        let url = ""
        if (this.props.data.type === 2) {
            //编辑部门
            url = api.api_URL + "/admin/dept/updateDepartmentInfo"
            let {param} = this.state
            param.departmentId = this.props.data.gridList.departmentId            //部门ID
            param.thirdDepartmentId = this.props.data.gridList.thirdDepartmentId  //同步第三方组织机构ID
            param.pcode = this.props.data.gridList.pcode                          //部门父ID
            param.thirdFactoryId = this.props.data.gridList.thirdFactoryId          //同步第三方厂区机构ID
            param.createTime = this.props.data.gridList.createTime                  //创建时间
            param.gid = this.props.data.gridList.gid                                //同步第三方公司机构ID
            param.guiKouFlag = this.props.data.gridList.guiKouFlag                  //归口部门标识符
            this.setState({param}, () => {
                this.addDepartment(url)
            })
        } else {
            url = api.api_URL + "/admin/dept/addDepartmentInfo"
            if (this.props.data.type === 1) {
                //新增部门
                let {param} = this.state
                param.guiKouFlag = "1"                                              //非归口部门
                param.departmentId = ""
                param.pcode = ""
                this.setState({param}, () => {
                    this.addDepartment(url)
                })
            } else {
                //新增子部门
                let {param} = this.state
                param.thirdFactoryId = this.props.data.gridList.thirdFactoryId    //关联同步的厂区ID
                param.pcode = this.props.data.gridList.code                       //部门父ID=部门ID
                param.gid = this.props.data.gridList.gid                          //公司编码
                param.guiKouFlag = "1"                                              //非归口部门
                param.departmentId = ""
                this.setState({param}, () => {
                    this.addDepartment(url)
                })
            }
        }
    }

    addDepartment(url) {
        const that = this;
        axios({
            method: 'POST',
            url: url,
            data: JSON.stringify(that.state.param),
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": "application/json;charset=UTF-8"
            },
        }).then(function (res) {
            message.success({content: "成功！"})
            that.handleCancel()
        }).catch(function (error) {
            console.log(error);
            message.error({content: "失败,请重新尝试！"})
        })
    }

    handleCancel = e => {
        console.log(e);
        this.props.handleCancel()
    };

    //获取公司下拉框值
    companySelect = [];

    getCompanySelect() {
        let that = this;
        let dataList = [];
        let url = api.api_URL + "/admin/company/queryAllCompanyInfoForSelect?orgCode=" + localStorage.getItem('orgCode');
        axios.get(url, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            if (res.data.code != 1) {
                message.success({content: "加载失败！"})
                return;
            }
            let companyInfoList = res.data.data.companyInfoList;
            for (let i = 0; i < companyInfoList.length; i++) {
                let comData = companyInfoList[i];
                const data = {};
                data.key = comData.thirdCompanyId;
                data.label = comData.companyName;
                dataList[i] = data;
            }
            for (let i = 0; i < dataList.length; i++) {
                that.companySelect.push(<Option key={dataList[i].key}>{dataList[i].label}</Option>);
            }

        }).catch(function (err) {
            console.log(err);
            message.success({content: "加载失败！"})
        })

    }

    //获取厂区下拉框值
    factorySelect = [];

    //选择公司
    companyChange = () => {
        this.props.form.resetFields('thirdFactoryId', []);
        this.factorySelect = [];
        let that = this;
        let dataList = [];
        let url = api.api_URL + "/admin/factory/queryFactoryInfoForSelect?orgCode=" + localStorage.getItem('orgCode');
        axios.get(url, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            if (res.data.code != 1) {
                alert(res.data.msg);
                return;
            }
            let factoryInfoList = res.data.data.factoryInfoList;
            if (factoryInfoList.length <= 0) {
                console.log("没有厂房数据")
                return;
            }
            for (let i = 0; i < factoryInfoList.length; i++) {
                let facData = factoryInfoList[i];
                const data = {};
                data.key = facData.thirdFactoryId;
                data.label = facData.name;
                console.log(data)
                dataList[i] = data;
            }
            console.log(("companyChange:" + dataList))

            for (let i = 0; i < dataList.length; i++) {
                that.factorySelect.push(<Option key={dataList[i].key}>{dataList[i].label}</Option>);
            }

        }).catch(function (err) {
            console.log(err);
        })
    }

    render() {
        const {getFieldDecorator, getFieldError} = this.props.form
        return (
            <div>
                <Modal
                    title={this.props.data.title}
                    visible={this.props.data.visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                >
                    <Form name="control-ref" autoComplete="off" ref={this.formRef}
                          labelCol={{span: 4}}
                          wrapperCol={{span: 18}}
                    >
                        {/*{this.props.data.isParent ?*/}
                            {/*<FormItem label="公司名称" name="gid">*/}
                                {/*{getFieldDecorator("gid", {*/}
                                    {/*rules: [*/}
                                        {/*{*/}
                                            {/*required: true,*/}
                                            {/*message: "请选择公司名称"*/}
                                        {/*}*/}
                                    {/*]*/}
                                {/*})(*/}
                                    {/*<Select placeholder={"请选择公司"} onChange={this.companyChange}*/}
                                             {/*allowClear >*/}
                                        {/*{this.companySelect}*/}
                                    {/*</Select>*/}
                                {/*)}*/}
                            {/*</FormItem> : <div></div>}*/}
                        {this.props.data.isParent ? <FormItem label="公司名称" name="thirdFactoryId">
                            {getFieldDecorator("thirdFactoryId", {
                                rules: [
                                    {
                                        required: true,
                                        message: "请选择公司名称"
                                    }
                                ]
                            })(
                                <Select showSearch={true} optionFilterProp="children" placeholder={"请选择公司"} onChange={this.factoryChange}
                                         allowClear >
                                    {this.factorySelect}
                                </Select>
                            )}
                        </FormItem> : <div></div>}
                        <FormItem label="部门编码" name="code">
                            {getFieldDecorator("code", {
                                rules: [
                                    {
                                        required: true,
                                        message: "请输入部门编码"
                                    }
                                ]
                            })(
                                <Input
                                    disabled={this.props.data.type=="2" ? true : false}/>
                            )}
                        </FormItem>
                        <FormItem label="部门名称" name="fullName">
                            {getFieldDecorator("fullName", {
                                rules: [
                                    {
                                        required: true,
                                        message: "请输入部门名称"
                                    }
                                ]
                            })(
                                <Input/>
                            )}
                        </FormItem>
                        <FormItem label="部门简称" name="name">
                            {getFieldDecorator("name", {
                                rules: [
                                    {
                                        required: true,
                                        message: "请输入部门简称"
                                    }
                                ]
                            })(
                                <Input/>
                            )}
                        </FormItem>
                    </Form>
                </Modal>
            </div>
        );
    }
}

export default Model